package com.axxc.jpa.web;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.UriComponentsBuilder;

import com.axxc.jpa.entity.ArticleEntity;
import com.axxc.jpa.service.IArticleService;


@Controller
@RequestMapping("article")
public class ArticleController {
	@Autowired
	private IArticleService articleService;
	
	@GetMapping("/{id}")
	public ResponseEntity<ArticleEntity> getArticleById(@PathVariable("id") Long id) {
		ArticleEntity article = articleService.getArticleById(id);
		return new ResponseEntity<ArticleEntity>(article, HttpStatus.OK);
	}
	@GetMapping("allArticles")
	public ResponseEntity<List<ArticleEntity>> getAllArticles() {
		List<ArticleEntity> list = articleService.getAllArticles();
		return new ResponseEntity<List<ArticleEntity>>(list, HttpStatus.OK);
	}
	@PostMapping("add")
	public ResponseEntity<Void> addArticle(@RequestBody ArticleEntity article, UriComponentsBuilder builder) {
		ArticleEntity savedArticle = articleService.addArticle(article);  
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(builder.path("/article/{id}").buildAndExpand(savedArticle.getArticleId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
	}
	@PutMapping("update")
	public ResponseEntity<ArticleEntity> updateArticle(@RequestBody ArticleEntity article) {
		articleService.updateArticle(article);
		return new ResponseEntity<ArticleEntity>(article, HttpStatus.OK);
	}
	@DeleteMapping("/{id}")
	public ResponseEntity<Void> deleteArticle(@PathVariable("id") Long id) {
		articleService.deleteArticle(id);
		return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
	}	
} 